﻿CREATE PROCEDURE [acms].[ExceptionLog_Put]
	@ServerName varchar(50),
	@ApplicationRoot varchar(50),
	@Url varchar(255),
	@RawUrl varchar(255),
	@PostId int,
	@SiteId int,
	@ExceptionType varchar(255),
	@ExceptionMessage varchar(2000),
	@InnerExceptionType varchar(255),
	@InnerExceptionMessage varchar(2000),
	@Source varchar(100),
	@StackTrace varchar(2000),
	@Created datetime,
	@IdOut int output
AS

	if(@ApplicationRoot = '/')
		set @ApplicationRoot = ''
	if (@SiteId is null or @SiteId = 0) and @ServerName is not null and @ApplicationRoot is not null begin
		select @SiteId = Id
		from Sites
		Where Root = @ServerName + @ApplicationRoot
	end
	
	if (@PostId is null or @PostId = 0) and @ServerName is not null and @ApplicationRoot is not null and @RawUrl is not null begin
		declare @Path varchar(255)
		set @Path = @RawUrl
		--remove query string
		if CHARINDEX('?', @Path) > 0
			set @Path = Left(@Path, CHARINDEX('?', @Path) - 1)

		--remove defulat or file type
		if CHARINDEX('/default.aspx', @Path) > 0
			set @Path = Left(@Path, Len(@Path) - 13)
		else if CHARINDEX('.', @Path) > 0
			set @Path = Left(@Path, Len(@Path) - CHARINDEX('.', Reverse(@Path)))
			
		--make rel to application root
		set @Path = SubString(@Path, Len(@ApplicationRoot) + 1, Len(@Path) - Len(@ApplicationRoot))
		set @Path = '~' + @Path

		select @PostId = a.Id
		from Post_View a
			inner join Site_View b on a.SiteId = b.Id
		where 
			b.Root = @ServerName + @ApplicationRoot
			and isNull(ParentPath, '') + a.Name = @Path
	end

	Insert ExceptionLog
		(ServerName, ApplicationRoot, Url, RawUrl, PostId, SiteId, ExceptionType, ExceptionMessage, InnerExceptionType, InnerExceptionMessage, Source, StackTrace, Created)
	Values
		(@ServerName, @ApplicationRoot, @Url, @RawUrl, @PostId, @SiteId, @ExceptionType, @ExceptionMessage, @InnerExceptionType, @InnerExceptionMessage, @Source, @StackTrace, @Created)
	Set @IdOut = @@Identity
RETURN 0;